Calculate Distance Between Two Points

Theory:

The distance between two points in a two-dimensional space can be calculated using the distance formula:

distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)

Python Code:

from math import sqrt

def calculate_distance(x1, y1, x2, y2):
    return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

# Taking input for coordinates and calculating distance
def calculate_and_display_distance():
    x1 = float(input("Enter the x-coordinate of the first point: "))
    y1 = float(input("Enter the y-coordinate of the first point: "))
    x2 = float(input("Enter the x-coordinate of the second point: "))
    y2 = float(input("Enter the y-coordinate of the second point: "))
    distance = calculate_distance(x1, y1, x2, y2)
    print("The distance between the two points is:", distance)

calculate_and_display_distance()

Example Output 1:

Enter the x-coordinate of the first point: 2

Enter the y-coordinate of the first point: 3

Enter the x-coordinate of the second point: 5

Enter the y-coordinate of the second point: 7

The distance between the two points is: 5.0

Example Output 2:

Enter the x-coordinate of the first point: 0

Enter the y-coordinate of the first point: 0

Enter the x-coordinate of the second point: 3

Enter the y-coordinate of the second point: 4

The distance between the two points is: 5.0

Code Explanation:

The function calculate_distance(x1, y1, x2, y2) calculates the distance between two points using the distance formula.

The function calculate_and_display_distance() takes input for the coordinates of two points, calculates the distance between them, and displays the result.